package com.ma.admin.handler

import com.ma.admin.model.User
import org.springframework.stereotype.Component
import xyz.erupt.annotation.`fun`.DataProxy
import xyz.erupt.core.exception.EruptWebApiRuntimeException
import java.util.regex.Pattern

/**
 * 用户管理修改数据时对部分数据进行校验
 *
 * @author yong
 * @date 2021/2/6 15:51
 */
@Component
class UserDataProxy : DataProxy<User> {
    /**
     * 在进行数据更新前对一些更改的字段进行数据校验
     *
     * @param user 用户
     * @author yong
     * @date 2021/2/6 21:56
     * @return void
     */
    override fun beforeUpdate(user: User) {

        //校验手机号
        val userPhone = user.userPhone
        val regexPhone = "0?(13|14|15|18|17)[0-9]{9}"
        val pattern = Pattern.compile(regexPhone)
        val matcher = pattern.matcher(userPhone)
        if (!matcher.matches())
            throw EruptWebApiRuntimeException("请请输入正确的手机号!")

        //校验邮箱
        val userEmail = user.userEmail
        val regexEmail = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$".toRegex()
        if (!userEmail.matches(regexEmail))
            throw EruptWebApiRuntimeException("请请输入正确的邮箱号!")

        //校验身份证号
        val userIdentityNum = user.userIdentityNum
        val regexIdentity = "^\\d{15}|\\d{18}$".toRegex()
        if (!userIdentityNum.matches(regexIdentity))
            throw EruptWebApiRuntimeException("请请输入正确的身份证号!")

        //校验性别
        val userSex = user.userSex
        if (userSex != "男" && userSex != "女")
            throw EruptWebApiRuntimeException("请请输入正确的性别!")
    }
}